'''Node querying via the Planet Lab RPC protocol.'''

import xmlrpclib

def get_hostnames(node_slice='usf_ubcslice5'):
    auth = {'Username':"yanhero@interchange.ubc.ca", 
        'AuthString':"eece411",
        'AuthMethod':"password"}

    server = xmlrpclib.ServerProxy('https://www.planet-lab.org/PLCAPI/')

    # Get the node ids associated with our slice
    node_ids = server.GetSlices(auth, node_slice, ['node_ids'])
    node_list = node_ids[0]['node_ids']
    total_nodes = len(node_list)
    print 'Retrieved',total_nodes,'node IDs. Expanding:'

    # Get the hostname associated with each node id
    node_hostnames=[]
    print'\tN/TOT\tID\tHOSTNAME (STATUS)'
    for i,node in enumerate(node_list[:]):
        node_info = server.GetNodes(auth,node, ['boot_state', 'hostname'])
        if len(node_info) > 0:
            #print str(node) +  ": "
            #print node_info[0]['hostname']
            hostname,state = node_info[0]['hostname'],node_info[0]['boot_state']
            hostname = hostname.lower()
            print '\t%d/%d\t%d\t%s (%s)' % (i+1, total_nodes, 
                                                node, hostname, state)
            node_hostnames.append( hostname )
    print len(node_hostnames),'node hostnames retrieved!'

    return node_hostnames
